import { useRef, useState } from 'react';
import type { DraggableData, DraggableEvent } from 'react-draggable';
import React from 'react';

interface UseDraggableProps {
  draggable?: boolean;
  onDragStart?: (event: DraggableEvent, data: DraggableData) => void;
  title?: React.ReactNode;
}

interface UseDraggableReturn {
  draggleRef: React.RefObject<HTMLDivElement>;
  disabled: boolean;
  bounds: { left: number; top: number; bottom: number; right: number };
  handleDragStart: (event: DraggableEvent, uiData: DraggableData) => void;
  renderDraggableTitle: () => React.ReactNode;
}

export function useDraggable({ draggable, onDragStart, title }: UseDraggableProps): UseDraggableReturn {
  const draggleRef = useRef<HTMLDivElement>(null);
  const [disabled, setDisabled] = useState(true);
  const [bounds, setBounds] = useState({ left: 0, top: 0, bottom: 0, right: 0 });

  const handleDragStart = (event: DraggableEvent, uiData: DraggableData) => {
    if (!draggable) return;

    const { clientWidth, clientHeight } = window.document.documentElement;
    const targetRect = draggleRef.current?.getBoundingClientRect();
    if (!targetRect) {
      return;
    }
    setBounds({
      left: -targetRect.left + uiData.x,
      right: clientWidth - (targetRect.right - uiData.x),
      top: -targetRect.top + uiData.y,
      bottom: clientHeight - (targetRect.bottom - uiData.y),
    });
    onDragStart?.(event, uiData);
  };

  const renderDraggableTitle = () => {
    if (!draggable || !title) return title;

    return (
      <div
        style={{ width: '100%', cursor: 'move' }}
        onMouseOver={() => {
          if (disabled) {
            setDisabled(false);
          }
        }}
        onMouseOut={() => {
          setDisabled(true);
        }}
        onFocus={() => {}}
        onBlur={() => {}}
      >
        {title}
      </div>
    );
  };

  return {
    draggleRef,
    disabled,
    bounds,
    handleDragStart,
    renderDraggableTitle,
  };
} 